package com.cyzy.homework.repository;

import com.cyzy.homework.entity.LeaveRequest;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;

import java.time.LocalDate;
import java.util.List;
import java.util.Optional;

/**
 * 请假申请Repository
 */
@Repository
public interface LeaveRequestRepository extends JpaRepository<LeaveRequest, Long> {
    
    /**
     * 根据用户ID查询请假申请列表
     */
    Page<LeaveRequest> findByUserIdOrderByApplyTimeDesc(String userId, Pageable pageable);
    
    /**
     * 根据班级ID查询请假申请列表
     */
    Page<LeaveRequest> findByClassIdOrderByApplyTimeDesc(String classId, Pageable pageable);
    
    /**
     * 根据状态查询请假申请列表
     */
    Page<LeaveRequest> findByStatusOrderByApplyTimeDesc(Integer status, Pageable pageable);
    
    /**
     * 根据班级ID和状态查询请假申请列表
     */
    Page<LeaveRequest> findByClassIdAndStatusOrderByApplyTimeDesc(String classId, Integer status, Pageable pageable);
    
    /**
     * 根据用户ID和状态查询请假申请列表
     */
    Page<LeaveRequest> findByUserIdAndStatusOrderByApplyTimeDesc(String userId, Integer status, Pageable pageable);
    
    /**
     * 检查用户在指定日期范围内是否有请假申请
     */
    @Query("SELECT lr FROM LeaveRequest lr WHERE lr.userId = :userId " +
           "AND lr.status IN (0, 1) " +
           "AND ((lr.startDate <= :endDate AND lr.endDate >= :startDate))")
    List<LeaveRequest> findOverlappingLeaveRequests(@Param("userId") String userId,
                                                  @Param("startDate") LocalDate startDate,
                                                  @Param("endDate") LocalDate endDate);
    
    /**
     * 统计用户的请假申请数量
     */
    long countByUserId(String userId);
    
    /**
     * 统计用户指定状态的请假申请数量
     */
    long countByUserIdAndStatus(String userId, Integer status);
    
    /**
     * 统计班级的请假申请数量
     */
    long countByClassId(String classId);
    
    /**
     * 统计班级指定状态的请假申请数量
     */
    long countByClassIdAndStatus(String classId, Integer status);
    
    /**
     * 查找用户在指定日期的当前生效的请假申请
     */
    @Query("SELECT lr FROM LeaveRequest lr WHERE lr.userId = :userId " +
           "AND lr.status = 1 " +
           "AND lr.startDate <= :currentDate AND lr.endDate >= :currentDate")
    Optional<LeaveRequest> findCurrentActiveLeaveByUserId(@Param("userId") String userId, 
                                                        @Param("currentDate") LocalDate currentDate);
}


